<template>
  <div class="user">
    <!--搜索表单-->
    <div class="common-seach-wrap">
      <el-form :inline="true" :model="formInline" class="demo-form-inline">
        <el-form-item label="">
          <el-input
            v-model="formInline.name"
            placeholder="产品名称"
            style="width: 200px"
          ></el-input>
        </el-form-item>
        <el-form-item label="">
          <el-select v-model="formInline.type" placeholder="产品类型" style="width: 200px">
            <el-option label="车衣" value="车衣" />
            <el-option label="窗膜" value="窗膜" />
          </el-select>
        </el-form-item>
        <el-form-item label="">
          <el-select v-model="formInline.sort" filterable placeholder="排序方式">
            <el-option
              v-for="item in sortOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="getTableInfo()">搜索</el-button>
          <el-button type="primary" icon="Plus" @click="handleInfo()">添加</el-button>
          <el-button type="success" icon="Download" @click="handleExport()">导出Excel</el-button>
          <el-button type="warning" icon="Upload" @click="handleImport()">导入Excel</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="count-tip">
      当前显示: {{ tableData.length }} 个价格策略(共 {{ totalDataNumber }} 个价格策略)
    </div>
    <div class="chart-box" v-loading="dataLoading">
      <div class="chart-title">
        <div class="chart-title-left">产品数据统计</div>
        <div class="chart-title-right">
          <el-switch v-model="chartSwitch" active-text="显示图表" inactive-text="隐藏图表" />
          <el-button
            type=""
            icon="Refresh"
            @click="getData()"
            size="small"
            style="margin-left: 10px"
            >刷新数据</el-button
          >
        </div>
      </div>
      <div class="card-box">
        <el-card shadow="hover">
          <div class="card-icon" style="background: #409eff">
            <el-icon color="#fff">
              <Money />
            </el-icon>
          </div>
          <div class="card-val">
            <div class="val">{{ totalDataNumber }}</div>
            <div class="label">总产品数</div>
          </div>
        </el-card>
        <el-card shadow="hover">
          <div class="card-icon" style="background: #67c23a">
            <el-icon color="#fff">
              <Van />
            </el-icon>
          </div>
          <div class="card-val">
            <div class="val">
              {{ allProducts.filter((item: any) => item.type == "窗膜").length }}
            </div>
            <div class="label">窗膜产品数量</div>
          </div>
        </el-card>
        <el-card shadow="hover">
          <div class="card-icon" style="background: #e6a23c">
            <el-icon color="#fff">
              <Box />
            </el-icon>
          </div>
          <div class="card-val">
            <div class="val">
              {{ allProducts.filter((item: any) => item.type == "窗膜").length }}
            </div>
            <div class="label">车衣产品数量</div>
          </div>
        </el-card>
        <el-card shadow="hover">
          <div class="card-icon" style="background: #f56c6c">
            <el-icon color="#fff">
              <PriceTag />
            </el-icon>
          </div>
          <div class="card-val">
            <div class="val">{{ averageYear }}</div>
            <div class="label">平均质保年限</div>
          </div>
        </el-card>
      </div>
      <div class="chart-main" v-show="chartSwitch">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-card shadow="hover">
              <template v-slot:header>
                <div class="chart-header">
                  <div class="chart-header-title">产品类型分布</div>
                  <el-icon size="16" @click="getData1()">
                    <Refresh />
                  </el-icon>
                </div>
              </template>
              <div id="productTypeChart" style="width: 100%; height: 300px"></div>
            </el-card>
          </el-col>
          <el-col :span="12">
            <el-card shadow="hover">
              <template v-slot:header>
                <div class="chart-header">
                  <div class="chart-header-title">质保年限分布</div>
                  <el-icon size="16" @click="getData2()">
                    <Refresh />
                  </el-icon>
                </div>
              </template>
              <!-- 添加价格区间分布图容器 -->
              <div id="priceRangeChart" style="width: 100%; height: 300px"></div>
            </el-card>
          </el-col>
        </el-row>
        <el-row style="margin-top: 20px">
          <el-col :span="24">
            <el-card shadow="hover">
              <template v-slot:header>
                <div class="chart-header">
                  <div class="chart-header-title">产品特性统计</div>
                  <el-icon size="16" @click="getData3()">
                    <Refresh />
                  </el-icon>
                </div>
              </template>
              <!-- 添加品牌分布图容器 -->
              <div id="brandChart" style="width: 100%; height: 400px"></div>
            </el-card>
          </el-col>
        </el-row>
      </div>
    </div>
    <!--内容-->
    <div class="product-content">
      <div class="table-wrap">
        <el-table size="small" :data="tableData" border style="width: 100%">
          <el-table-column prop="id" label="ID" width="80"></el-table-column>
          <el-table-column prop="name" label="产品名称"></el-table-column>
          <el-table-column prop="firstletter" label="产品图片" width="400">
            <template #default="scope">
              <el-image
                :src="scope.row.image_url"
                :preview-src-list="[scope.row.image_url]"
                :preview-teleported="true"
                style="width: 100px"
              ></el-image>
            </template>
          </el-table-column>
          <el-table-column prop="" label="产品类型">
            <template #default="{ row }">
              <el-tag v-if="row.type == '窗膜'" type="primary" size="small">窗膜</el-tag>
              <el-tag v-else type="success" size="small">车衣</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="material" label="材质"></el-table-column>
          <el-table-column prop="" label="质保年限">
            <template #default="{ row }"> {{ row.warranty_years }}年 </template>
          </el-table-column>
          <el-table-column prop="" label="产品特性">
            <template #default="{ row }">
              <el-tag
                v-for="(c, index) in row.features"
                :key="index"
                type="primary"
                :style="{ marginRight: '5px' }"
              >
                {{ c }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="" label="覆盖部位">
            <template #default="{ row }">
              <el-tag
                v-for="(c, index) in row.parts"
                :key="index"
                type="warning"
                :style="{ marginRight: '5px' }"
              >
                {{ c }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template #default="scope">
              <el-button type="primary" icon="Edit" size="small" @click="handleInfo(scope.row)"
                >编辑</el-button
              >
              <el-button
                type="danger"
                icon="Delete"
                size="small"
                @click="handleDelete(scope.row.id)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!--分页-->
      <div class="pagination">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          background
          :current-page="curPage"
          :page-size="pageSize"
          layout="total,sizes, prev, pager, next, jumper"
          :total="totalDataNumber"
        ></el-pagination>
      </div>
    </div>
    <productDialog ref="productDialogRef" @getTable="getTableInfo"></productDialog>
    <el-dialog v-model="importVisible" title="导入产品数据" width="500px">
      <el-upload
        ref="uploadRef"
        :action="importProductApi"
        :headers="headers"
        :drag="true"
        accept=".xlsx,.xls"
        :auto-upload="false"
        @success="handleUploadSuccess"
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">拖拽文件到此处或点击上传</div>
        <template #tip>
          <div class="el-upload__tip">
            <p>只支持Excel文件(.xlsx, .xls)</p>
            <p>必填字段: 产品名称、产品类型、材质、质保年限</p>
            <p>非必填字段:产品特性、覆盖部位、产品图片</p>
            <p style="color: red">
              注意:产品特性和覆盖部位需要用逗号分隔（如：自修复,防刮,防污,前杠,前机盖,车顶）
            </p>
            <p style="color: red">
              <el-icon color="red"><Warning /></el-icon
              >导入类型只能是车衣或窗膜，如需添加额外产品类型请联系开发者
            </p>
          </div>
          <el-button type="primary" @click="handleDownloadTemplate()">下载模板</el-button>
        </template>
      </el-upload>
      <template #footer>
        <el-button @click="importVisible = false">取消</el-button>
        <el-button type="primary" @click="doImport">确认导入</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { computed, nextTick, onMounted, onUnmounted, provide, ref, watch } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { deleteProductApi, getProductListApi } from "@/api/carfilm/quote";
import productDialog from "./components/productDialog.vue";
import * as echarts from "echarts";
import axios from "axios";
import { useUserStore } from "@/store";
const dataLoading = ref(true);
const loading = ref(true);
const tableData = ref<any[]>([]);
const pageSize = ref(10);
const totalDataNumber = ref(0);
const curPage = ref(1);
const productDialogRef = ref<any>(null);
const formInline = ref({
  name: "",
  type: "",
  sort: "",
});
watch(
  () => formInline.value,
  () => {
    getTableInfo();
  },
  {
    deep: true,
  }
);
const allProducts = ref<any[]>([]);
const sortOptions = ref([
  { label: "ID 升序", value: "id_asc" },
  { label: "ID 降序", value: "id_desc" },
  { label: "名称升序", value: "name_asc" },
  { label: "名称降序", value: "name_desc" },
  { label: "类型升序", value: "type_asc" },
  { label: "类型降序", value: "type_desc" },
]);
const chartSwitch = ref(true);
const getData = () => {
  dataLoading.value = true;
  getProductListApi({
    page: 1,
    limit: 9999,
  }).then((res: any) => {
    dataLoading.value = false;
    allProducts.value = res.data?.list;
    // 更新图表数据
    getData1();
    getData2();
    getData3();
  });
};
//平均价格
const averageYear = computed(() => {
  if (allProducts.value.length == 0) return 0;
  return (
    allProducts.value.reduce((acc: number, cur: any) => {
      return acc + parseInt(cur.warranty_years);
    }, 0) / allProducts.value.length
  ).toFixed(0);
});
/******************图表********************* */
const myChart1 = ref<any>(null);
const myChart2 = ref<any>(null);
const myChart3 = ref<any>(null);

// 初始化图表
const initCharts = () => {
  myChart1.value = echarts.init(document.getElementById("productTypeChart"));
  myChart2.value = echarts.init(document.getElementById("priceRangeChart"));
  myChart3.value = echarts.init(document.getElementById("brandChart"));
  // 确保图表撑满容器
  setTimeout(() => {
    myChart1.value?.resize();
    myChart2.value?.resize();
    myChart3.value?.resize();
    chartSwitch.value = false;
  }, 100);
};
//获取图表数据
const getData1 = () => {
  const typeCount: Record<string, number> = {};
  allProducts.value.forEach((item: any) => {
    typeCount[item.type] = (typeCount[item.type] || 0) + 1;
  });
  let option_data = Object.keys(typeCount).map((name) => ({
    name,
    value: typeCount[name],
  }));
  // 清除之前的图表数据
  myChart1.value?.clear();
  const option = {
    tooltip: {
      trigger: "item",
    },
    legend: {
      // Try 'horizontal'
      orient: "vertical",
      right: 10,
      top: "center",
    },
    series: [
      {
        name: "",
        type: "pie",
        radius: ["40%", "70%"],
        data: option_data,
      },
    ],
  };
  // 指定图表的配置项和数据
  myChart1.value.setOption(option, true);
};
const getData2 = () => {
  //质保年限分布
  const yearsCount: any = {};
  allProducts.value.forEach((item: any) => {
    yearsCount[item.warranty_years + "年"] = (yearsCount[item.warranty_years + "年"] || 0) + 1;
  });

  // 将年限数据转换为数组并按年份升序排序
  const sortedYearsData = Object.keys(yearsCount)
    .map((yearKey) => ({
      name: yearKey,
      value: yearsCount[yearKey],
    }))
    .sort((a, b) => {
      // 提取年份数字进行比较
      const yearA = parseInt(a.name);
      const yearB = parseInt(b.name);
      return yearA - yearB;
    });

  // 清除之前的图表数据
  myChart2.value?.clear();
  // 配置柱状图选项
  const option = {
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "shadow",
      },
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      containLabel: true,
    },
    xAxis: {
      type: "category",
      data: sortedYearsData.map((item) => item.name),
      axisTick: {
        alignWithLabel: true,
      },
    },
    yAxis: {
      type: "value",
    },
    series: [
      {
        name: "质保年限",
        type: "bar",
        barWidth: "60%",
        data: sortedYearsData.map((item) => item.value),
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: "#83bff6" },
            { offset: 0.5, color: "#188df0" },
            { offset: 1, color: "#188df0" },
          ]),
        },
        emphasis: {
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: "#2378f7" },
              { offset: 0.7, color: "#2378f7" },
              { offset: 1, color: "#83bff6" },
            ]),
          },
        },
        label: {
          show: true,
          position: "top",
          formatter: "{c}",
        },
      },
    ],
  };

  // 设置图表选项
  myChart2.value?.setOption(option, true);
};
const getData3 = () => {
  // 产品特性统计
  const featureCountMap: Record<string, number> = {};

  allProducts.value.forEach((item: any) => {
    // 遍历每个产品的特性数组
    if (item.features && Array.isArray(item.features)) {
      item.features.forEach((feature: string) => {
        featureCountMap[feature] = (featureCountMap[feature] || 0) + 1;
      });
    }
  });

  // 转换为数组并按数量降序排序
  const featureCountData = Object.keys(featureCountMap).map((feature) => ({
    name: feature,
    value: featureCountMap[feature],
  }));

  // 按数量从高到低排序
  featureCountData.sort((a, b) => b.value - a.value);

  // 只取前10个特性
  const top10Features = featureCountData.slice(0, 10);

  // 清除之前的图表数据
  myChart3.value?.clear();
  // 配置柱状图选项
  const option = {
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "shadow",
      },
      formatter: "{b}<br/>{a}: {c}个产品",
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "10%",
      containLabel: true,
    },
    xAxis: {
      type: "category",
      data: top10Features.map((item) => item.name),
      axisTick: {
        alignWithLabel: true,
      },
      axisLabel: {
        rotate: 45,
        interval: 0,
      },
    },
    yAxis: {
      type: "value",
      axisLabel: {
        formatter: "{value} 个产品",
      },
    },
    series: [
      {
        name: "产品数量",
        type: "bar",
        barWidth: "60%",
        data: top10Features.map((item) => item.value),
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: "#83bff6" },
            { offset: 0.5, color: "#188df0" },
            { offset: 1, color: "#188df0" },
          ]),
        },
        emphasis: {
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: "#2378f7" },
              { offset: 0.7, color: "#2378f7" },
              { offset: 1, color: "#83bff6" },
            ]),
          },
        },
        label: {
          show: true,
          position: "top",
          formatter: "{c}",
        },
      },
    ],
  };

  // 设置图表选项
  myChart3.value?.setOption(option, true);
};
onMounted(() => {
  getData();
  getTableInfo();
  // 初始化图表
  nextTick(() => {
    initCharts();
  });
});
const handleSizeChange = (val: number) => {
  pageSize.value = val;
  getTableInfo();
};
const handleCurrentChange = (val: number) => {
  curPage.value = val;
  getTableInfo();
};
function getTableInfo() {
  loading.value = true;
  getProductListApi({
    page: curPage.value,
    limit: pageSize.value,
    ...formInline.value,
  }).then((res: any) => {
    tableData.value = res.data?.list;
    totalDataNumber.value = res.data?.total;
    loading.value = false;
  });
}
const handleInfo = (row?: any) => {
  productDialogRef.value.dialogOpen(row);
};

const handleDelete = (id: number) => {
  ElMessageBox.confirm("确认要删除该产品吗?", "警告！", {
    confirmButtonText: "确认删除",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      deleteProductApi(id).then((res: any) => {
        getTableInfo();
        ElMessage({
          type: "success",
          message: "删除成功！",
        });
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "删除已取消",
      });
    });
};
const handleExport = async () => {
  ElMessage({
    type: "info",
    message: "正在导出",
  });
  try {
    const userStore = useUserStore();
    const { token } = userStore;
    const response = await axios({
      method: "GET",
      url: "/api/index.php/carfilm.product/export",
      responseType: "blob",
      headers: {
        token: token,
      },
    });
    let filename = "产品数据_" + new Date().getTime() + ".xlsx";
    // 创建并触发下载
    const url = window.URL.createObjectURL(new Blob([response.data]));
    const link = document.createElement("a");
    link.href = url;
    link.setAttribute("download", filename);
    document.body.appendChild(link);
    link.click();

    // 清理资源
    link.remove();
    window.URL.revokeObjectURL(url);
    ElMessage({
      type: "success",
      message: "导出成功",
    });
  } catch (error) {
    console.error("下载失败:", error);
    ElMessage.error("文件下载失败");
  }
};
//导入
const importVisible = ref(false);
const uploadRef = ref<any>(null);
const importProductApi = ref("/api/index.php/carfilm.product/import");
const headers = computed(() => {
  return {
    "Content-Type": "multipart/form-data",
    token: useUserStore().token,
  };
});
const handleImport = () => {
  importVisible.value = true;
};
const doImport = () => {
  uploadRef.value!.submit();
};
const handleUploadSuccess = (res: any, file: any) => {
  ElMessage({
    type: "success",
    message: "导入成功",
  });
  importVisible.value = false;
};
const handleDownloadTemplate = async () => {
  try {
    ElMessage({
      type: "info",
      message: "正在下载模板",
    });

    // 使用 fetch 获取文件内容
    const response = await fetch("/static/product_template.xlsx");
    const blob = await response.blob();

    // 创建 blob URL
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement("a");
    link.href = url;
    link.download = "产品导入模板.xlsx";
    link.style.display = "none";

    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);

    // 释放 blob URL
    window.URL.revokeObjectURL(url);

    ElMessage({
      type: "success",
      message: "下载成功",
    });
  } catch (error) {
    console.error("下载失败:", error);
    ElMessage.error("模板下载失败");
  }
};
</script>
<style lang="scss" scoped>
.advanced-search-panel {
  background-color: #f5f7fa;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  margin: 10px 0;
  padding: 15px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  animation: fadeIn-1b06b556 0.3s ease-in-out;
  width: 100%;
  flex-shrink: 0;
}

.count-tip {
  margin-top: 12px;
  color: #909399;
  font-size: 13px;
}

.letter-box {
  margin-top: 10px;
  margin-bottom: 10px;
  display: flex;
  align-items: center;
  flex-wrap: wrap;

  .letter-item {
    padding: 5px 10px;
    margin-top: 5px;
    cursor: pointer;
    margin-right: 5px;
    border: 1px solid #d9ecff;
    border-radius: 4px;

    &.active {
      background-color: #409eff;
      color: #fff;
    }
  }
}

.count-box {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: 10px;
}

.brand-item {
  margin-bottom: 35px;
  background-color: #fff;
  border-radius: 6px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  padding: 24px;
  transition: all 0.3s;

  .brand-info {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 22px;
    padding-bottom: 12px;
    border-bottom: 1px solid #ebeef5;

    .brand-left {
      display: flex;
      align-items: center;

      .brand-name {
        margin: 0 15px 0 15px;
        font-size: 18px;
        font-weight: 500;
        color: #303133;
      }
    }
  }
}

.tag-box {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  margin-top: 10px;

  .el-tag {
    margin-right: 5px;
  }
}

.chart-box {
  margin-top: 20px;
  padding-bottom: 30px;

  .chart-title {
    display: flex;
    align-items: center;
    justify-content: space-between;

    .chart-title-left {
      margin: 0;
      font-size: 18px;
      font-weight: 600;
      color: #303133;
    }
  }

  .card-box {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    justify-content: space-between;
    flex-shrink: 0;

    .el-card {
      width: 23%;
      margin-top: 20px;

      ::v-deep(.el-card__body) {
        display: flex !important;
        align-items: center;

        .card-icon {
          width: 60px;
          height: 60px;
          border-radius: 50%;
          display: flex;
          justify-content: center;
          align-items: center;
          margin-right: 15px;
        }

        .card-val {
          .val {
            font-size: 24px;
            font-weight: 600;
            color: #303133;
            line-height: 1.2;
          }

          .label {
            font-size: 14px;
            color: #909399;
            margin-top: 5px;
          }
        }
      }
    }
  }
}

.chart-main {
  margin-top: 20px;

  .chart-header {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .chart-header-title {
      font-size: 16px;
      font-weight: 600;
      color: #303133;
    }
  }
}
</style>
